<template style="width: 913px">
  <el-header style="padding: 0;margin: 0">
    <el-affix :offset="0">
      <div id="headDiv">
        <div>
          <el-button type="warning" size="large" style="margin-left: 40px" @click="$router.push('app')" round>
            <el-icon>
              <House/>
            </el-icon>
            首页
          </el-button>
        </div>
        <div>
          <span style="color: #626262;margin-right: 20px">您好!</span>
          <el-button type="primary" size="large" @click="$router.push('goods')" round>全部商品</el-button>
          <el-button type="primary" size="large" @click="toShoppingCar()" round>购物车</el-button>
          <el-button size="large" type="primary" @click="toOrder()" round>个人订单</el-button>
          <el-button size="large" type="primary" @click="$router.push('user')" round>个人信息</el-button>
          <el-button size="large" type="primary" @click="$router.push('returnOrder')" round>
            退款订单管理
          </el-button>
          <el-button size="large" type="primary" @click="$router.push('userMoney')" round>预存款管理</el-button>
          <el-button size="large" type="danger" style="margin-right: 20px" @click="exitUser()" round>退出登录
          </el-button>
        </div>
      </div>
    </el-affix>
  </el-header>

  <div style="height: auto;margin: 0 auto;">
    <div style="font-size: 30px;margin: 20px 0">
      <a href="#" style="color:#545454;text-decoration: none;">LO<span style="color: #c4c4c4">V</span><span>O</span> |
        朗沃商城</a>
    </div>
  </div>
  <div style="height: auto;margin: 0 auto">
    <el-menu v-model="queryMenu" mode="horizontal" default-active="1">
      <el-menu-item index="1" @click="selectAllOrder()">所有订单</el-menu-item>
      <el-menu-item index="2" @click="selectAllOrder(0)">待付款</el-menu-item>
      <el-menu-item index="3" @click="selectAllOrder(1)">已付款</el-menu-item>
      <el-menu-item index="4" @click="selectAllOrder(2)">已完成</el-menu-item>
      <el-menu-item index="5" @click="selectAllOrder(3)">已取消</el-menu-item>
    </el-menu>
    <el-main>
      <el-table :data="orderList">
        <el-table-column label="订单编号" prop="orderNo" align="center"></el-table-column>
        <el-table-column label="订单总价格" prop="orderTotalPrice" align="center"></el-table-column>
        <el-table-column label="订单实付价格" prop="orderPrice" align="center"></el-table-column>
        <el-table-column label="下单时间" prop="orderPayTime" align="center"></el-table-column>
        <el-table-column label="支付方式" prop="payMethod" align="center">
          <template #default="order">
            <span v-if="order.row.payMethod===1">预存款</span>
            <span v-if="order.row.payMethod===0">支付宝</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" prop="orderStatus" align="center">
          <template #default="order">
            <span v-if="order.row.orderStatus===1">已付款</span>
            <span v-if="order.row.orderStatus===0">未付款</span>
            <span v-if="order.row.orderStatus===2">完成</span>
            <span v-if="order.row.orderStatus===3">取消</span>
          </template>
        </el-table-column>
        <el-table-column v-if="tag===0" prop="orderCountDown" label="支付倒计时" align="center">
          <template #default="order">
            <span style="color: red">{{ order.row.orderCountDown }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="200px">
          <template #default="order">
            <div style="display: flex;justify-content: center">
              <!--              <div :hidden="orderPay" style="margin-right: 10px">
                              <el-button type="danger">支付</el-button>
                            </div>-->
              <el-button type="primary" style="margin-right: 10px" @click="queryDetailOrder(order.row)">订单详情
              </el-button>
              <!--              <el-button type="danger" icon="el-icon-delete" circle></el-button>-->
              <el-button type="danger" @click="deleteOrder(order.row.orderNo)">
                <el-icon>
                  <DeleteFilled/>
                </el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <!-- 分页部分 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                   v-model:total="total" background @current-change="selectAllOrder(tag)"/>
  </div>
  <div>
    <el-dialog
        title="订单详细"
        v-model="showOrderDetail"
        width="65%"
        :before-close="handleClose"
    >
      <div style="display: flex;justify-content: space-around;font-size: 16px">
        <div>
          <p>订单编号：{{ orderRow.orderNo }}</p>
          <p>订单总价格：{{ orderRow.orderTotalPrice }}元</p>
          <p>订单实付价格：{{ orderRow.orderPrice }}元</p>
          <p>下单时间：{{ orderRow.orderPayTime }}</p>
          <p v-if="orderRow.payMethod===0">支付方式：支付宝</p>
          <p v-else-if="orderRow.payMethod===1">支付方式：预存款</p>
        </div>
        <div>
          <p v-if="orderRow.orderStatus===0">订单状态：未付款</p>
          <p v-if="orderRow.orderStatus===1">订单状态：已付款</p>
          <p v-if="orderRow.orderStatus===2">订单状态：完成</p>
          <p v-if="orderRow.orderStatus===3">订单状态：取消</p>
          <p>收货人名字：{{ orderRow.receiverName }}</p>
          <p>收货人手机号码：{{ orderRow.receiverPhone }}</p>
          <p>收货地址区域：{{ orderRow.receiverRegion }}</p>
          <p>收货详细地址：{{ orderRow.receiverAddress }}</p>
        </div>
      </div>
      <el-table :data="orderDetailList">
        <el-table-column label="商品名称" prop="goodsName" align="center"></el-table-column>
        <el-table-column label="商品类型" prop="goodsType" align="center"></el-table-column>
        <el-table-column label="商品规格" prop="goodsSize" align="center"></el-table-column>
        <el-table-column label="商品图片" prop="goodsPic" align="center">
          <template #default="orderDetail">
            <img :src="goodsImgPath+orderDetail.row.goodsPic" alt="" style="width: 50px;height: 50px">
          </template>
        </el-table-column>
        <el-table-column label="购买数量" prop="goodsNum" align="center"></el-table-column>
        <el-table-column label="商品销售价格" prop="goodsPrice" align="center"></el-table-column>
        <el-table-column label="商品实际支付价格" prop="goodsPayPrice" align="center"></el-table-column>
        <el-table-column label="是否发货" align="center">
          <template #default="orderDetail">
            <span v-if="orderDetail.row.onDelievery===1">已发货</span>
            <span v-if="orderDetail.row.onDelievery===0">未发货</span>
          </template>
        </el-table-column>
        <el-table-column label="是否为退货商品" prop="onReturn" align="center">
          <template #default="orderDetail">
            <span v-if="orderDetail.row.onReturn===1">退货商品</span>
            <span v-if="orderDetail.row.onReturn===0">非退货</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="300px" fixed="right">
          <template #default="orderDetail">
            <div style="display: flex;justify-content: center">
              <div
                  v-if="orderDetail.row.onDelievery===1&&orderDetail.row.onTake===0&&orderRow.orderStatus===1&&orderDetail.row.onReturn===0"
                  style="margin-right: 10px">
                <el-button type="danger" @click="ackTake(orderDetail.row)">收货</el-button>
              </div>
              <!--              <el-button type="primary" @click="">查看商品</el-button>-->
              <!-- 申请退单个商品 -->
              <el-button type="warning" @click="returnGoods(orderDetail.row)"
                         :disabled="orderRow.orderStatus===0||orderRow.orderStatus===3||orderDetail.row.onReturn===1">
                申请退货
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
    <span class="dialog-footer">
      <el-button round type="warning" @click="returnAll(orderRow)"
                 :disabled="this.returnAble===false||orderRow.orderStatus===0||orderRow.orderStatus===3">申请退货</el-button>
      <el-button round type="primary" @click="showOrderDetail = false">确 定</el-button>
    </span>
      </template>
    </el-dialog>
  </div>

  <!-- 申请退货对话框 -->
  <el-dialog v-model="returnVisible" title="填写退货原因" width="40%">
    <el-input oninput="value=value.replace(/\s*/g,'')" v-model="returnOrder.returnReason"
              placeholder="请输入退货原因" style="width: 148px"/>
    <template #footer>
      <span class="dialog-center">
        <el-button @click="submit()" type="primary" round>确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 申请退货对话框end -->

</template>

<script>
import axios from "axios";
import {ElMessage} from "element-plus";

export default {
  name: "Order",
  data() {
    return {
      userToken: "",
      userNo: '',
      goodsImgPath: '/picture/face/',
      orderList: [
        // {productName:"笔记本",orderNumber:"bijiben202302281503",orderTime:"2023-02-28 15:03:46",orderPay:"预存款支付",orderAddress:"四川省成都市武侯区",orderPrice:8000},
        // {productName:"汉堡包",orderNumber:"hanbaobao202201081228",orderTime:"2023-02-28 15:03:46",orderPay:"支付宝支付",orderAddress:"四川省成都市武侯区",orderPrice:48.5},
        // {productName:"笔记本",orderNumber:"bijiben202302281503",orderTime:"2023-02-28 15:03:46",orderPay:"预存款支付",orderAddress:"四川省成都市武侯区",orderPrice:10000},
      ],
      orderPay: true,
      showOrderDetail: false,
      orderRow: {},
      receiver: true,
      orderDetailList: [],
      queryMenu: 1,
      // 退货原因对话框是否显示
      returnVisible: false,
      // 退货订单
      returnOrder: {
        userId: sessionStorage.getItem("userId"),
        returnOrderNo: "",
        buyOrderNo: "",
        originMoney: 0,
        payMethod: 0,
        payMoney: 0,
        returnReason: "",
        returnTime: null,
        returnStatus: 0,
      },
      // 退货商品列表
      returnGoodsList: [],
      // 退货标识位: 退整个订单为true, 退单个商品为false
      flag: true,
      // 是否可以退货标识位: 允许退货true, 不允许退货false
      returnAble: true,
      // 订单商品编号
      orderGoodsNo: "",
      tag: 0,//显示类型
      currentPage: 1,//分页当前页
      pageSize: 3,//分页每页多少条
      total: 0,
    }
  },
  created() {
    let userToken = sessionStorage.getItem("userToken")
    let userNo = sessionStorage.getItem("userNo")
    if (userToken == null) {
      this.$router.push("login")
    } else {
      this.userToken = userToken
      this.userNo = userNo;
    }
    this.selectAllOrder();
  },
  methods: {
    //退出登录
    exitUser() {
      sessionStorage.clear();
      this.$router.push("newLogin")
    },
    selectAllOrder(tag) {
      this.tag = tag;
      if (tag === 0) {
        this.orderPay = false;
      } else {
        this.orderPay = true;
      }
      let param = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        data: {
          startTime: '',
          endTime: '',
          orderStatus: tag,
          userNo: this.userNo,
        }
      }
      axios.post('api/order/queryOrder', param).then(p => {
        this.orderList = p.data.data.records
        this.total = p.data.data.total
        let that = this;
        if (tag === 0) {
          if (this.ticker) {
            clearInterval(this.ticker);
          }
          this.ticker = setInterval(function () {
            for (let i = 0; i < that.orderList.length; i++) {
              that.orderList[i].orderCountDown = that.countDown(that.orderList[i].orderPayTime);
              if (that.orderList[i].orderCountDown === '0时0分0秒') {
                that.selectAllOrder(that.tag)
                clearInterval(that.ticker);
              }
            }
          }, 1000);
        }
      });
    },
    queryDetailOrder(orderRow) {
      this.orderRow = orderRow;
      // 重置整个订单退货申请
      this.returnAble = true;
      console.log(this.orderRow)
      // 获取该订单的订单编号和支付方式
      this.returnOrder.buyOrderNo = orderRow.orderNo;
      this.returnOrder.payMethod = orderRow.payMethod;
      axios.get('api/orderGoods/queryOrderGoodsByOrderNo?orderNo=' + orderRow.orderNo).then(p => {
        this.orderDetailList = p.data.data;
        // 如果该订单中有的商品都为退货商品则不允许用户发起整个订单的退货申请
        this.orderDetailList.forEach(g => {
          if (g.onReturn === 1) {
            this.returnAble = false;
          }
        });
        this.showOrderDetail = true;
      })
    },
    // 申请退整个订单
    returnAll(order) {
      // 重置退货商品列表和订单商品编号
      this.returnGoodsList = [];
      this.orderGoodsNo = "";
      // 获取退货商品列表
      this.orderDetailList.forEach(g => {
        this.returnGoodsList.push({
          goodsNo: g.goodsNo,
          goodsName: g.goodsName,
          buyNum: g.goodsNum
        });
      })
      this.flag = true;
      // 更新退货订单的信息
      this.returnOrder.originMoney = order.orderTotalPrice;
      this.returnOrder.payMoney = order.orderPrice;
      // 申请退货弹窗展示
      this.returnVisible = true;
      // 关闭详情弹窗
      this.showOrderDetail = false;
    },
    // 申请退单个商品
    returnGoods(goods) {
      // 重置退货商品列表和订单商品编号
      this.returnGoodsList = [];
      this.orderGoodsNo = "";
      // 获取订单商品编号
      this.orderGoodsNo = goods.orderGoodsNo;
      // 获取该退货商品
      this.returnGoodsList.push({
        goodsNo: goods.goodsNo,
        goodsName: goods.goodsName,
        buyNum: goods.goodsNum
      });
      this.flag = false;
      // 更新退货订单的信息
      this.returnOrder.originMoney = goods.goodsPrice;
      this.returnOrder.payMoney = goods.goodsPayPrice;
      // 申请退货弹窗展示
      this.returnVisible = true;
    },
    // 确定退货
    submit() {
      if (this.returnOrder.returnReason === "") {
        ElMessage.warning("退货原因不能为空");
        return;
      }
      // 设置退货申请时间
      this.returnOrder.returnTime = this.getTime();
      // 设置请求参数
      let param = new URLSearchParams();
      param.append("returnOrderString", JSON.stringify(this.returnOrder));
      param.append("returnOrderListString", JSON.stringify(this.returnGoodsList));
      param.append("orderGoodsNo", this.orderGoodsNo);
      axios.post("/api/returnOrder/saveReturnOrderToFront", param, this.config).then(response => {
        if (response.data.code === 200) {
          // 关闭申请退货弹窗
          this.returnVisible = false;
          // 重置退货申请标识位
          this.queryDetailOrder(this.orderRow);
        } else {
          ElMessage.error(response.data.msg);
        }
      })
    },
    // 获取当前时间
    getTime() {
      let d = new Date();
      let year = d.getFullYear();
      let mon = d.getMonth() + 1;
      let day = d.getDate();
      let hour = d.getHours();
      let minute = d.getMinutes();
      let second = d.getSeconds();
      return year + "-" + (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day) + ' '
          + (hour < 10 ? ('0' + hour) : hour) + ':' + (minute < 10 ? ('0' + minute) : minute) + ':' + (second < 10 ? ('0' + second) : second);
    },
    deleteOrder(orderNo) {
      axios.delete('api/order/deleteOrderByOrderNo?orderNo=' + orderNo).then(p => {
        if (p.data.code === 200) {
          ElMessage.success(p.data.msg);
          this.selectAllOrder(this.tag);
        } else {
          ElMessage.error(p.data.msg)
        }
      })
    },
    ackTake(row) {
      axios.get('api/orderGoods/updateOrderGoodsTakeStateByGoodsNo?orderGoodsNo=' + row.orderGoodsNo).then(p => {
        if (p.data.code) {
          axios.get('api/orderGoods/queryOrderGoodsByOrderNo?orderNo=' + row.orderNo).then(p => {
            this.orderDetailList = p.data.data;
            // 如果该订单中有的商品都为退货商品则不允许用户发起整个订单的退货申请
            this.orderDetailList.forEach(g => {
              if (g.onReturn === 1) {
                this.returnAble = false;
              }
            });
            this.showOrderDetail = true;
          });
          this.selectAllOrder(this.tag)
        }
      })
    },
    //时间倒计时
    countDown(rowTime) {
      let orderTime = new Date(rowTime);
      let timePoor = orderTime.setMinutes(orderTime.getMinutes() + 30);
      //console.log(new Date(timePoor))
      let date = new Date();
      let poorTime = timePoor - date;
      if (poorTime >= 0) {
        //console.log('进入判断')
        let d = Math.floor(poorTime / 1000 / 60 / 60 / 24);
        let h = Math.floor(poorTime / 1000 / 60 / 60 % 24);
        let m = Math.floor(poorTime / 1000 / 60 % 60);
        let s = Math.floor(poorTime / 1000 % 60);
        return h + '时' + m + '分' + s + '秒'
      } else {
        return '0时0分0秒'
      }
    },
    toShoppingCar() {
      let str = sessionStorage.getItem("user")
      let user = JSON.parse(str)
      console.log(user)
      if (user.auditStatus === 1) {
        this.$router.push('shoppingCar')
      } else {
        ElMessage.error("用户资质还未通过")
      }
    },
    toOrder() {
      let str = sessionStorage.getItem("user")
      let user = JSON.parse(str)
      console.log(user)
      if (user.auditStatus === 1) {
        this.$router.push('order')
      } else {
        ElMessage.error("用户资质还未通过")
      }
    },

  }
}
</script>

<style>
#headDiv {
  width: 100%;
  background-color: white;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 5px 10px gray;
}
</style>